/**
 * Program  : EvacuationMapTask.java
 * Author   : long
 * Create   : 2016年5月14日 下午3:11:21
 *
 * Copyright 2016 by Embedded Internet Solutions Inc.,
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of Embedded Internet Solutions Inc.("Confidential Information").  
 * You shall not disclose such Confidential Information and shall 
 * use it only in accordance with the terms of the license agreement 
 * you entered into with Embedded Internet Solutions Inc.
 *
 */
	
package cn.broadin.app.hotel.task;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.AsyncTask;
import cn.broadin.app.hotel.util.XLog;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

/**
 * 
 * 下载疏散图线程
 * 
 * @author   long
 * @version  1.0.0
 * @date 2016年5月14日下午3:11:21
 */
public class AdvDownloadTask extends AsyncTask<String[], Void, Void>{

	private static final String TAG = "AdvDownloadTask";
	private Activity mActivity;
	
	private GifImageView mGifImageView;
	private byte[] bytes;
	
	@SuppressLint("HandlerLeak")
	public AdvDownloadTask(Activity activity, GifImageView gifImageView) {
		XLog.d("AdvDownloadTask start.");
		this.mActivity = activity;
		this.mGifImageView = gifImageView;
	}
	
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	@Override
	protected Void doInBackground(String[]... params) {
		XLog.i(TAG, "path: " + params[0][0]);
		downFile(params[0][0]);
		return null;
	}
	
	@Override
	protected void onPostExecute(Void result) {
		try {
			GifDrawable gifFrom = new GifDrawable(bytes);
			mGifImageView.setImageDrawable(gifFrom);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void downFile(String downPath) {
		XLog.i(TAG, "downFile path : " + downPath);
		HttpURLConnection conn = null;
		try {
			URL url = new URL(downPath);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5000);
			long length = conn.getContentLength();
			XLog.i(TAG, "downFile size is : " + length);
			bytes = readInputSteam(conn.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
			XLog.e(TAG, "downFile error. " + e.getMessage());
		} finally {
			if(conn != null){
				conn.disconnect();  
			}
		} 
	}
	
	public static final byte[] readInputSteam(InputStream inStream)   throws IOException {  
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();  
        byte[] buff = new byte[100];  
        int rc = 0;  
        while ((rc = inStream.read(buff, 0, 100)) > 0) {  
            swapStream.write(buff, 0, rc);  
        }  
        byte[] in2b = swapStream.toByteArray();  
        return in2b;  
    } 
}

